package com.smart.community.user.service.impl;

import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.cache.DataScopeInfo;
import com.smart.community.commons.enums.RoleCodeEnum;
import com.smart.community.commons.enums.SystemStatusEnum;
import com.smart.community.commons.exception.BusinessException;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.feign.property.service.DataScopeFeign;
import com.smart.community.user.entity.UserPropertyCompany;
import com.smart.community.user.dto.LoginDTO;
import com.smart.community.user.dto.UserDTO;
import com.smart.community.user.dto.UserQueryDTO;
import com.smart.community.user.dto.UserProfileUpdateDTO;
import com.smart.community.user.entity.LoginLog;
import com.smart.community.user.entity.User;
import com.smart.community.user.entity.UserRole;
import com.smart.community.user.mapper.UserMapper;
import com.smart.community.user.service.CacheService;
import com.smart.community.user.service.RoleService;
import com.smart.community.user.service.UserPropertyCompanyService;
import com.smart.community.user.service.UserRoleService;
import com.smart.community.user.service.UserService;
import com.smart.community.user.mapper.LoginLogMapper;
import com.smart.community.user.mapper.UserPropertyCompanyMapper;
import com.smart.community.user.vo.UserPropertyCompanyVO;
import com.smart.community.user.vo.UserVO;

import io.seata.spring.annotation.GlobalTransactional;

/**
 * 用户服务实现
 *
 * @author Wu.Liang
 * @since 2025-07-05
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private UserPropertyCompanyService userPropertyCompanyService;
    
    @Autowired
    private DataScopeFeign dataScopeFeign;
    
    @Autowired
    private LoginLogMapper loginLogMapper;
    
    @Autowired
    private UserPropertyCompanyMapper userPropertyCompanyMapper;

    // ==================== 缓存常量定义 ====================
    private static final String USER_CACHE_PREFIX = "user:";
    private static final String USER_ID_CARD_CACHE_PREFIX = "user:idcard:";
    private static final String USER_PHONE_CACHE_PREFIX = "user:phone:";
    private static final String USER_USERNAME_CACHE_PREFIX = "user:username:";
    private static final String USER_EMAIL_CACHE_PREFIX = "user:email:";
    private static final String USER_ROLES_CACHE_PREFIX = "user:roles:";
    private static final String USER_PROPERTY_COMPANIES_CACHE_PREFIX = "user:property:companies:";
    private static final String PROPERTY_COMPANY_USERS_CACHE_PREFIX = "property:company:users:";
    private static final String USER_UNIQUE_CHECK_CACHE_PREFIX = "user:unique:check:";
    
    // 缓存过期时间（秒）
    private static final long USER_CACHE_EXPIRE = 3600; // 1小时
    private static final long USER_ROLES_CACHE_EXPIRE = 1800; // 30分钟
    private static final long USER_PROPERTY_COMPANIES_CACHE_EXPIRE = 1800; // 30分钟
    private static final long PROPERTY_COMPANY_USERS_CACHE_EXPIRE = 1800; // 30分钟
    private static final long UNIQUE_CHECK_CACHE_EXPIRE = 300; // 5分钟

    // ==================== 缓存工具方法 ====================
    
    /**
     * 清除用户相关缓存
     */
    private void clearUserCache(Long userId) {
        try {
            String[] cacheKeys = {
                USER_CACHE_PREFIX + userId,
                USER_ROLES_CACHE_PREFIX + userId,
                USER_PROPERTY_COMPANIES_CACHE_PREFIX + userId
            };
            
            for (String cacheKey : cacheKeys) {
                cacheService.delete(cacheKey);
            }
            
            log.debug("清除用户缓存成功，用户ID：{}", userId);
        } catch (Exception e) {
            log.warn("清除用户缓存失败，用户ID：{}", userId, e);
        }
    }
    
    /**
     * 清除用户唯一性检查缓存
     */
    private void clearUserUniqueCheckCache(String value, String type) {
        try {
            String cacheKey = USER_UNIQUE_CHECK_CACHE_PREFIX + type + ":" + value;
            cacheService.delete(cacheKey);
            log.debug("清除用户唯一性检查缓存成功，类型：{}，值：{}", type, value);
        } catch (Exception e) {
            log.warn("清除用户唯一性检查缓存失败，类型：{}，值：{}", type, value, e);
        }
    }
    
    /**
     * 清除物业公司用户列表缓存
     */
    private void clearPropertyCompanyUsersCache(Long propertyCompanyId) {
        try {
            String cacheKey = PROPERTY_COMPANY_USERS_CACHE_PREFIX + propertyCompanyId;
            cacheService.delete(cacheKey);
            log.debug("清除物业公司用户列表缓存成功，物业公司ID：{}", propertyCompanyId);
        } catch (Exception e) {
            log.warn("清除物业公司用户列表缓存失败，物业公司ID：{}", propertyCompanyId, e);
        }
    }

    @Override
    public Map<String, Object> login(LoginDTO loginDTO) throws Exception {
        log.info("用户登录请求: username={}", loginDTO.getUsername());
        
        // 1. 验证用户名是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, loginDTO.getUsername());
        User user = this.getOne(queryWrapper);
        
        if (user == null) {
            log.warn("登录失败: 用户名不存在, username={}", loginDTO.getUsername());
            throw new BusinessException("用户名或密码错误");
        }
        
        // 2. 检查用户状态
        if (user.getStatus() == null || user.getStatus() != 1) {
            log.warn("登录失败: 用户状态异常, username={}, status={}", loginDTO.getUsername(), user.getStatus());
            throw new BusinessException("用户已被禁用或锁定");
        }
        
        // 3. 验证密码
        String encryptedPassword = SecurityUtils.encryptPassword(loginDTO.getPassword());
        if (!encryptedPassword.equals(user.getPassword())) {
            log.warn("登录失败: 密码错误, username={}", loginDTO.getUsername());
            throw new BusinessException("用户名或密码错误");
        }
        
        // 4. 获取用户角色和权限
        List<Map<String, Object>> roles = getUserRoles(user.getId());
        List<Map<String, Object>> menus = getUserMenus(user.getId());
        
        // 5. 使用Sa-Token登录
        SecurityUtils.login(user.getId());
        String token = SecurityUtils.getTokenValue();
        
        // 6. 记录登录日志
        try {
            LoginLog loginLog = new LoginLog();
            loginLog.setUserId(user.getId());
            loginLog.setUsername(user.getUsername());
            loginLog.setLoginTime(LocalDateTime.now());
            loginLog.setLoginIp("127.0.0.1"); // 暂时使用默认IP，后续可从请求中获取真实IP
            loginLog.setLoginAddress("未知");
            loginLog.setBrowser("未知");
            loginLog.setOs("未知");
            loginLog.setLoginStatus(0); // 0表示成功
            loginLog.setLoginMessage("登录成功");
            loginLog.setStatus(1);
            loginLogMapper.insert(loginLog);
        } catch (Exception e) {
            log.warn("记录登录日志失败: {}", e.getMessage());
        }
        
        // 7. 构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", convertToUserVO(user));
        result.put("roles", roles);
        result.put("menus", menus);
        
        log.info("用户登录成功: username={}, userId={}", user.getUsername(), user.getId());
        return result;
    }

    @Override
    public void logout(Long userId) throws Exception {
        log.info("用户登出请求: userId={}", userId);
        
        try {
            // 1. 使用Sa-Token登出
            SecurityUtils.logout();
            
            // 2. 记录登出日志
            LoginLog loginLog = new LoginLog();
            loginLog.setUserId(userId);
            loginLog.setLogoutTime(LocalDateTime.now());
            loginLog.setLoginStatus(0); // 0表示成功
            loginLog.setLoginMessage("登出成功");
            loginLog.setStatus(1);
            loginLogMapper.insert(loginLog);
            
            log.info("用户登出成功: userId={}", userId);
        } catch (Exception e) {
            log.error("用户登出失败: userId={}, error={}", userId, e.getMessage());
            throw new BusinessException("登出失败: " + e.getMessage());
        }
    }

    @Override
    public IPage<User> getUserPage(UserQueryDTO queryDTO) throws Exception {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        
        // 1. 检查超级管理员权限
        Boolean isSuperAdmin = dataScopeFeign.isUserSuperAdmin(currentUserId);
        if (isSuperAdmin) {
            // 超级管理员可查看所有数据
            return getUserPageWithQuery(queryDTO);
        }
        
        // 2. 获取用户数据权限范围
        List<Long> communityIds = dataScopeFeign.getUserCommunityIds(currentUserId);
        if (communityIds.isEmpty()) {
            // 用户无权限访问任何社区数据
            return new Page<>(queryDTO.getCurrent(), queryDTO.getSize(), 0L);
        }
        
        // 3. 应用数据权限过滤
        return getUserPageWithPermission(queryDTO, communityIds);
    }
    
    /**
     * 带查询条件的分页查询（无权限限制）
     */
    private IPage<User> getUserPageWithQuery(UserQueryDTO queryDTO) {
        LambdaQueryWrapper<User> queryWrapper = buildQueryWrapper(queryDTO);
        Page<User> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        return this.page(page, queryWrapper);
    }
    
    /**
     * 带权限过滤的分页查询
     */
    private IPage<User> getUserPageWithPermission(UserQueryDTO queryDTO, List<Long> communityIds) {
        LambdaQueryWrapper<User> queryWrapper = buildQueryWrapper(queryDTO);
        queryWrapper.in(User::getCommunityId, communityIds);
        Page<User> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        return this.page(page, queryWrapper);
    }
    
    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<User> buildQueryWrapper(UserQueryDTO queryDTO) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        
        if (queryDTO.getUsername() != null && !queryDTO.getUsername().isEmpty()) {
            queryWrapper.like(User::getUsername, queryDTO.getUsername());
        }
        if (queryDTO.getRealName() != null && !queryDTO.getRealName().isEmpty()) {
            queryWrapper.like(User::getRealName, queryDTO.getRealName());
        }
        if (queryDTO.getPhone() != null && !queryDTO.getPhone().isEmpty()) {
            queryWrapper.like(User::getPhone, queryDTO.getPhone());
        }
        if (queryDTO.getEmail() != null && !queryDTO.getEmail().isEmpty()) {
            queryWrapper.like(User::getEmail, queryDTO.getEmail());
        }
        if (queryDTO.getUserType() != null) {
            queryWrapper.eq(User::getUserType, queryDTO.getUserType());
        }
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq(User::getStatus, queryDTO.getStatus());
        }
        
        return queryWrapper;
    }

    @Override
    @GlobalTransactional
    public void createUser(UserDTO userDTO) throws Exception {
        // 检查身份证号重复
        if (userDTO.getIdCard() != null && !userDTO.getIdCard().trim().isEmpty()) {
            if (!checkIdCardUnique(userDTO.getIdCard().trim(), null)) {
                throw new BusinessException("身份证号重复");
            }
        }
        
        // 检查手机号重复
        if (userDTO.getPhone() != null && !userDTO.getPhone().trim().isEmpty()) {
            if (!checkPhoneUnique(userDTO.getPhone().trim(), null)) {
                throw new BusinessException("手机号重复");
            }
        }
        
        // 设置默认值
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        if (user.getStatus() == null) {
            user.setStatus(1); // 默认启用
        }
        
        // 密码加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        
        this.save(user);
        
        // 清除相关缓存
        try {
            // 清除唯一性检查缓存
            if (userDTO.getIdCard() != null && !userDTO.getIdCard().trim().isEmpty()) {
                clearUserUniqueCheckCache(userDTO.getIdCard().trim(), "idcard");
            }
            if (userDTO.getPhone() != null && !userDTO.getPhone().trim().isEmpty()) {
                clearUserUniqueCheckCache(userDTO.getPhone().trim(), "phone");
            }
            if (userDTO.getEmail() != null && !userDTO.getEmail().trim().isEmpty()) {
                clearUserUniqueCheckCache(userDTO.getEmail().trim(), "email");
            }
            if (userDTO.getUsername() != null && !userDTO.getUsername().trim().isEmpty()) {
                clearUserUniqueCheckCache(userDTO.getUsername().trim(), "username");
            }
            
            // 如果用户关联了物业公司，清除物业公司用户列表缓存
            if (user.getPropertyCompanyId() != null) {
                clearPropertyCompanyUsersCache(user.getPropertyCompanyId());
            }
            
            log.debug("用户创建成功，已清除相关缓存，用户ID：{}", user.getId());
        } catch (Exception e) {
            log.warn("清除用户创建相关缓存失败，用户ID：{}", user.getId(), e);
        }
    }

    @Override
    @GlobalTransactional
    public void updateUser(UserDTO userDTO) throws Exception {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        
        // 1. 检查超级管理员权限
        Boolean isSuperAdmin = dataScopeFeign.isUserSuperAdmin(currentUserId);
        if (!isSuperAdmin) {
            // 2. 获取目标用户信息
            User targetUser = this.getById(userDTO.getId());
            if (targetUser == null) {
                throw new BusinessException("用户不存在");
            }
            
            // 3. 验证操作权限
            Boolean hasPermission = dataScopeFeign.hasPropertyCompanyPermission(
                currentUserId, targetUser.getPropertyCompanyId());
            
            if (!hasPermission) {
                throw new BusinessException("无权限操作该用户");
            }
        }
        
        // 检查身份证号重复
        if (userDTO.getIdCard() != null && !userDTO.getIdCard().trim().isEmpty()) {
            if (!checkIdCardUnique(userDTO.getIdCard().trim(), userDTO.getId())) {
                throw new BusinessException("身份证号重复");
            }
        }
        
        // 检查手机号重复
        if (userDTO.getPhone() != null && !userDTO.getPhone().trim().isEmpty()) {
            if (!checkPhoneUnique(userDTO.getPhone().trim(), userDTO.getId())) {
                throw new BusinessException("手机号重复");
            }
        }
        
        // 查询现有用户，保留版本号以确保乐观锁正常工作
        User existingUser = this.getById(userDTO.getId());
        if (existingUser == null) {
            throw new BusinessException("用户不存在");
        }
        
        BeanUtils.copyProperties(userDTO, existingUser);
        existingUser.setUpdateTime(LocalDateTime.now());
        this.updateById(existingUser);
        
        // 清除相关缓存
        try {
            // 清除用户基本信息缓存
            clearUserCache(existingUser.getId());
            
            // 清除唯一性检查缓存
            if (userDTO.getIdCard() != null && !userDTO.getIdCard().trim().isEmpty()) {
                clearUserUniqueCheckCache(userDTO.getIdCard().trim(), "idcard");
            }
            if (userDTO.getPhone() != null && !userDTO.getPhone().trim().isEmpty()) {
                clearUserUniqueCheckCache(userDTO.getPhone().trim(), "phone");
            }
            if (userDTO.getEmail() != null && !userDTO.getEmail().trim().isEmpty()) {
                clearUserUniqueCheckCache(userDTO.getEmail().trim(), "email");
            }
            if (userDTO.getUsername() != null && !userDTO.getUsername().trim().isEmpty()) {
                clearUserUniqueCheckCache(userDTO.getUsername().trim(), "username");
            }
            
            // 如果用户关联了物业公司，清除物业公司用户列表缓存
            if (existingUser.getPropertyCompanyId() != null) {
                clearPropertyCompanyUsersCache(existingUser.getPropertyCompanyId());
            }
            
            log.debug("用户更新成功，已清除相关缓存，用户ID：{}", existingUser.getId());
        } catch (Exception e) {
            log.warn("清除用户更新相关缓存失败，用户ID：{}", existingUser.getId(), e);
        }
    }

    @Override
    @GlobalTransactional
    public UserVO updateUserProfile(Long userId, UserProfileUpdateDTO updateDTO) throws Exception {
        // 获取用户信息
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 检查手机号重复（排除当前用户）
        if (updateDTO.getPhone() != null && !updateDTO.getPhone().trim().isEmpty()) {
            if (!checkPhoneUnique(updateDTO.getPhone().trim(), userId)) {
                throw new BusinessException("手机号重复");
            }
        }
        
        // 检查邮箱重复（排除当前用户）
        if (updateDTO.getEmail() != null && !updateDTO.getEmail().trim().isEmpty()) {
            if (!checkEmailUnique(updateDTO.getEmail().trim(), userId)) {
                throw new BusinessException("邮箱重复");
            }
        }
        
        // 更新用户信息
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setRealName(updateDTO.getRealName());
        // 昵称字段：如果提供了值就更新，包括空字符串
        if (updateDTO.getNickname() != null) {
            updateUser.setNickname(updateDTO.getNickname());
        } else {
            // 如果nickname为null，设置为空字符串
            updateUser.setNickname("");
        }
        updateUser.setPhone(updateDTO.getPhone());
        updateUser.setEmail(updateDTO.getEmail());
        updateUser.setAvatar(updateDTO.getAvatar());
        updateUser.setUpdateTime(LocalDateTime.now());
        updateUser.setUpdateBy(userId);
        
        // 保存更新
        boolean success = this.updateById(updateUser);
        if (!success) {
            throw new BusinessException("更新失败");
        }
        
        // 清除用户缓存
        clearUserCache(userId);
        
        // 清除唯一性检查缓存
        if (updateDTO.getPhone() != null && !updateDTO.getPhone().trim().isEmpty()) {
            clearUserUniqueCheckCache(updateDTO.getPhone().trim(), "phone");
        }
        if (updateDTO.getEmail() != null && !updateDTO.getEmail().trim().isEmpty()) {
            clearUserUniqueCheckCache(updateDTO.getEmail().trim(), "email");
        }
        
        // 返回更新后的用户信息
        User updatedUser = this.getById(userId);
        UserVO userVO = new UserVO();
        
        // 明确复制所有字段，确保nickname字段正确复制
        userVO.setId(updatedUser.getId());
        userVO.setUsername(updatedUser.getUsername());
        userVO.setNickname(updatedUser.getNickname());
        userVO.setRealName(updatedUser.getRealName());
        userVO.setPhone(updatedUser.getPhone());
        userVO.setEmail(updatedUser.getEmail());
        userVO.setAvatar(updatedUser.getAvatar());
        userVO.setUserType(updatedUser.getUserType());
        userVO.setStatus(updatedUser.getStatus());
        userVO.setCreateTime(updatedUser.getCreateTime());
        userVO.setUpdateTime(updatedUser.getUpdateTime());
        userVO.setLastLoginTime(updatedUser.getLastLoginTime());
        userVO.setLastLoginIp(updatedUser.getLastLoginIp());
        
        return userVO;
    }

    @Override
    @GlobalTransactional
    public void deleteUser(Long userId) throws Exception {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        
        // 1. 检查超级管理员权限
        Boolean isSuperAdmin = dataScopeFeign.isUserSuperAdmin(currentUserId);
        if (!isSuperAdmin) {
            // 2. 获取目标用户信息
            User targetUser = this.getById(userId);
            if (targetUser == null) {
                throw new BusinessException("用户不存在");
            }
            
            // 3. 验证操作权限
            Boolean hasPermission = dataScopeFeign.hasPropertyCompanyPermission(
                currentUserId, targetUser.getPropertyCompanyId());
            
            if (!hasPermission) {
                throw new BusinessException("无权限删除该用户");
            }
        }
        
        // 获取用户信息用于缓存清理
        User userToDelete = this.getById(userId);
        
        // 删除用户角色关联
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId);
        userRoleService.remove(queryWrapper);
        // 删除用户
        this.removeById(userId);
        
        // 清除相关缓存
        try {
            // 清除用户基本信息缓存
            clearUserCache(userId);
            
            // 清除用户角色缓存
            String userRolesCacheKey = USER_ROLES_CACHE_PREFIX + userId;
            cacheService.delete(userRolesCacheKey);
            
            // 清除用户物业公司关联缓存
            String userPropertyCompaniesCacheKey = USER_PROPERTY_COMPANIES_CACHE_PREFIX + userId;
            cacheService.delete(userPropertyCompaniesCacheKey);
            
            // 如果用户关联了物业公司，清除物业公司用户列表缓存
            if (userToDelete != null && userToDelete.getPropertyCompanyId() != null) {
                clearPropertyCompanyUsersCache(userToDelete.getPropertyCompanyId());
            }
            
            log.debug("用户删除成功，已清除相关缓存，用户ID：{}", userId);
        } catch (Exception e) {
            log.warn("清除用户删除相关缓存失败，用户ID：{}", userId, e);
        }
    }

    @Override
    @GlobalTransactional
    public void batchDeleteUsers(List<Long> userIds) throws Exception {
        // 获取用户信息用于缓存清理
        List<User> usersToDelete = this.listByIds(userIds);
        
        // 批量删除用户角色关联
        for (Long userId : userIds) {
            LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserRole::getUserId, userId);
            userRoleService.remove(queryWrapper);
        }
        // 批量删除用户
        this.removeByIds(userIds);
        
        // 清除相关缓存
        try {
            for (Long userId : userIds) {
                // 清除用户基本信息缓存
                clearUserCache(userId);
                
                // 清除用户角色缓存
                String userRolesCacheKey = USER_ROLES_CACHE_PREFIX + userId;
                cacheService.delete(userRolesCacheKey);
                
                // 清除用户物业公司关联缓存
                String userPropertyCompaniesCacheKey = USER_PROPERTY_COMPANIES_CACHE_PREFIX + userId;
                cacheService.delete(userPropertyCompaniesCacheKey);
            }
            
            // 清除物业公司用户列表缓存（去重）
            if (usersToDelete != null) {
                usersToDelete.stream()
                    .filter(user -> user.getPropertyCompanyId() != null)
                    .map(User::getPropertyCompanyId)
                    .distinct()
                    .forEach(this::clearPropertyCompanyUsersCache);
            }
            
            log.debug("批量删除用户成功，已清除相关缓存，用户ID列表：{}", userIds);
        } catch (Exception e) {
            log.warn("清除批量删除用户相关缓存失败，用户ID列表：{}", userIds, e);
        }
    }

    @Override
    @GlobalTransactional
    public void resetPassword(Long userId, String newPassword) throws Exception {
        // 查询现有用户，保留版本号以确保乐观锁正常工作
        User existingUser = this.getById(userId);
        if (existingUser == null) {
            throw new BusinessException("用户不存在");
        }
        
        existingUser.setPassword(SecurityUtils.encryptPassword(newPassword));
        existingUser.setUpdateTime(LocalDateTime.now());
        this.updateById(existingUser);
    }

    @Override
    @GlobalTransactional
    public void changePassword(Long userId, String oldPassword, String newPassword) throws Exception {
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 验证旧密码
        if (!SecurityUtils.verifyPassword(oldPassword, user.getPassword())) {
            throw new BusinessException("旧密码不正确");
        }
        
        // 更新密码
        user.setPassword(SecurityUtils.encryptPassword(newPassword));
        user.setUpdateTime(LocalDateTime.now());
        this.updateById(user);
    }

    @Override
    @GlobalTransactional
    public void enableUser(Long userId) throws Exception {
        updateUserStatus(userId, 1);
    }

    @Override
    @GlobalTransactional
    public void disableUser(Long userId) throws Exception {
        updateUserStatus(userId, 0);
    }

    @Override
    @GlobalTransactional
    public void lockUser(Long userId) throws Exception {
        updateUserStatus(userId, 2);
    }

    @Override
    @GlobalTransactional
    public void unlockUser(Long userId) throws Exception {
        updateUserStatus(userId, 1);
    }

    @Override
    @GlobalTransactional
    public void assignRoles(Long userId, List<Long> roleIds) throws Exception {
        // 第2步：物理删除用户旧的角色关联（必须使用DELETE语句物理删除）
        userRoleService.removeAllRolesFromUser(userId);
        
        // 第3步：添加新的角色关联
        if (roleIds != null && !roleIds.isEmpty()) {
            userRoleService.assignRolesToUser(userId, roleIds);
                    // 角色分配成功后，清除用户权限缓存和角色缓存
        clearUserPermissionCache(userId);
        
        // 清除用户角色缓存
        try {
            String userRolesCacheKey = USER_ROLES_CACHE_PREFIX + userId;
            cacheService.delete(userRolesCacheKey);
            log.debug("清除用户角色缓存成功，用户ID：{}", userId);
        } catch (Exception e) {
            log.warn("清除用户角色缓存失败，用户ID：{}", userId, e);
        }
        
        log.info("用户角色分配成功，已清除权限缓存，用户ID：{}，角色ID：{}", userId, roleIds);
        } else {
            // 如果没有分配任何角色，也要清除缓存
            clearUserPermissionCache(userId);
            log.info("用户角色已清空，已清除权限缓存，用户ID：{}", userId);
        }
    }
    
    /**
     * 清除用户权限缓存
     * 根据《智慧社区微服务架构总览.md》标准，确保权限缓存的一致性
     */
    private void clearUserPermissionCache(Long userId) {
        try {
            // 清除数据权限范围缓存
            String dataScopeCacheKey = "data_scope:user:" + userId;
            cacheService.delete(dataScopeCacheKey);
            
            // 清除其他相关权限缓存
            String[] cacheKeys = {
                "user:super:admin:" + userId,
                "user:data:scope:" + userId,
                "user:property:company:ids:" + userId,
                "user:community:ids:" + userId,
                "permission:menu:user:" + userId,
                "permission:data:scope:user:" + userId,
                "user:permissions:" + userId,
                "user:roles:" + userId
            };
            
            for (String cacheKey : cacheKeys) {
                cacheService.delete(cacheKey);
            }
            
            log.debug("已清除用户权限缓存，用户ID: {}", userId);
        } catch (Exception e) {
            log.warn("清除用户权限缓存失败，用户ID: {}", userId, e);
        }
    }

    @Override
    public List<Map<String, Object>> getUserRoles(Long userId) throws Exception {
        if (userId == null) {
            return new ArrayList<>();
        }
        
        String cacheKey = USER_ROLES_CACHE_PREFIX + userId;
        
        try {
            // 尝试从缓存获取
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> cachedRoles = cacheService.get(cacheKey, List.class);
            if (cachedRoles != null) {
                log.debug("从缓存获取用户角色成功，用户ID：{}", userId);
                return cachedRoles;
            }
            
            // 缓存未命中，从数据库查询
            List<UserRole> userRoles = userRoleService.getUserRolesByUserId(userId);
            List<Map<String, Object>> result = new ArrayList<>();
            for (UserRole userRole : userRoles) {
                Map<String, Object> roleMap = new HashMap<>();
                roleMap.put("roleId", userRole.getRoleId());
                roleMap.put("userId", userRole.getUserId());
                result.add(roleMap);
            }
            
            // 缓存查询结果
            cacheService.set(cacheKey, result, USER_ROLES_CACHE_EXPIRE);
            log.info("用户角色信息已缓存，用户ID：{}", userId);
            
            return result;
        } catch (Exception e) {
            log.warn("缓存操作失败，直接从数据库查询，用户ID：{}", userId, e);
            List<UserRole> userRoles = userRoleService.getUserRolesByUserId(userId);
            List<Map<String, Object>> result = new ArrayList<>();
            for (UserRole userRole : userRoles) {
                Map<String, Object> roleMap = new HashMap<>();
                roleMap.put("roleId", userRole.getRoleId());
                roleMap.put("userId", userRole.getUserId());
                result.add(roleMap);
            }
            return result;
        }
    }

    @Override
    public List<Map<String, Object>> getUserMenus(Long userId) throws Exception {
        // 临时实现，返回空列表
        return new ArrayList<>();
    }

    @Override
    public boolean checkUsernameUnique(String username, Long userId) throws Exception {
        if (username == null || username.trim().isEmpty()) {
            return true;
        }
        
        String usernameTrim = username.trim();
        String cacheKey = USER_UNIQUE_CHECK_CACHE_PREFIX + "username:" + usernameTrim + ":" + (userId != null ? userId : "null");
        
        try {
            // 尝试从缓存获取
            Boolean cachedResult = cacheService.get(cacheKey, Boolean.class);
            if (cachedResult != null) {
                log.debug("从缓存获取用户名唯一性检查结果，用户名：{}，用户ID：{}", usernameTrim, userId);
                return cachedResult;
            }
            
            // 缓存未命中，从数据库查询
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, usernameTrim);
            if (userId != null) {
                queryWrapper.ne(User::getId, userId);
            }
            boolean isUnique = this.count(queryWrapper) == 0;
            
            // 缓存查询结果
            cacheService.set(cacheKey, isUnique, UNIQUE_CHECK_CACHE_EXPIRE);
            log.debug("用户名唯一性检查结果已缓存，用户名：{}，用户ID：{}，结果：{}", usernameTrim, userId, isUnique);
            
            return isUnique;
        } catch (Exception e) {
            log.warn("缓存操作失败，直接从数据库查询，用户名：{}，用户ID：{}", usernameTrim, userId, e);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, usernameTrim);
            if (userId != null) {
                queryWrapper.ne(User::getId, userId);
            }
            return this.count(queryWrapper) == 0;
        }
    }

    @Override
    public boolean checkPhoneUnique(String phone, Long userId) throws Exception {
        if (phone == null || phone.trim().isEmpty()) {
            return true;
        }
        
        String phoneTrim = phone.trim();
        String cacheKey = USER_UNIQUE_CHECK_CACHE_PREFIX + "phone:" + phoneTrim + ":" + (userId != null ? userId : "null");
        
        try {
            // 尝试从缓存获取
            Boolean cachedResult = cacheService.get(cacheKey, Boolean.class);
            if (cachedResult != null) {
                log.debug("从缓存获取手机号唯一性检查结果，手机号：{}，用户ID：{}", phoneTrim, userId);
                return cachedResult;
            }
            
            // 缓存未命中，从数据库查询
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phoneTrim);
            if (userId != null) {
                queryWrapper.ne(User::getId, userId);
            }
            boolean isUnique = this.count(queryWrapper) == 0;
            
            // 缓存查询结果
            cacheService.set(cacheKey, isUnique, UNIQUE_CHECK_CACHE_EXPIRE);
            log.debug("手机号唯一性检查结果已缓存，手机号：{}，用户ID：{}，结果：{}", phoneTrim, userId, isUnique);
            
            return isUnique;
        } catch (Exception e) {
            log.warn("缓存操作失败，直接从数据库查询，手机号：{}，用户ID：{}", phoneTrim, userId, e);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phoneTrim);
            if (userId != null) {
                queryWrapper.ne(User::getId, userId);
            }
            return this.count(queryWrapper) == 0;
        }
    }

    @Override
    public boolean checkEmailUnique(String email, Long userId) throws Exception {
        if (email == null || email.trim().isEmpty()) {
            return true;
        }
        
        String emailTrim = email.trim();
        String cacheKey = USER_UNIQUE_CHECK_CACHE_PREFIX + "email:" + emailTrim + ":" + (userId != null ? userId : "null");
        
        try {
            // 尝试从缓存获取
            Boolean cachedResult = cacheService.get(cacheKey, Boolean.class);
            if (cachedResult != null) {
                log.debug("从缓存获取邮箱唯一性检查结果，邮箱：{}，用户ID：{}", emailTrim, userId);
                return cachedResult;
            }
            
            // 缓存未命中，从数据库查询
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail, emailTrim);
            if (userId != null) {
                queryWrapper.ne(User::getId, userId);
            }
            boolean isUnique = this.count(queryWrapper) == 0;
            
            // 缓存查询结果
            cacheService.set(cacheKey, isUnique, UNIQUE_CHECK_CACHE_EXPIRE);
            log.debug("邮箱唯一性检查结果已缓存，邮箱：{}，用户ID：{}，结果：{}", emailTrim, userId, isUnique);
            
            return isUnique;
        } catch (Exception e) {
            log.warn("缓存操作失败，直接从数据库查询，邮箱：{}，用户ID：{}", emailTrim, userId, e);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail, emailTrim);
            if (userId != null) {
                queryWrapper.ne(User::getId, userId);
            }
            return this.count(queryWrapper) == 0;
        }
    }

    @Override
    public boolean checkIdCardUnique(String idCard, Long userId) throws Exception {
        if (idCard == null || idCard.trim().isEmpty()) {
            return true;
        }
        
        String idCardTrim = idCard.trim();
        String cacheKey = USER_UNIQUE_CHECK_CACHE_PREFIX + "idcard:" + idCardTrim + ":" + (userId != null ? userId : "null");
        
        try {
            // 尝试从缓存获取
            Boolean cachedResult = cacheService.get(cacheKey, Boolean.class);
            if (cachedResult != null) {
                log.debug("从缓存获取身份证号唯一性检查结果，身份证号：{}，用户ID：{}", idCardTrim, userId);
                return cachedResult;
            }
            
            // 缓存未命中，从数据库查询
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getIdCard, idCardTrim);
            if (userId != null) {
                queryWrapper.ne(User::getId, userId);
            }
            boolean isUnique = this.count(queryWrapper) == 0;
            
            // 缓存查询结果
            cacheService.set(cacheKey, isUnique, UNIQUE_CHECK_CACHE_EXPIRE);
            log.debug("身份证号唯一性检查结果已缓存，身份证号：{}，用户ID：{}，结果：{}", idCardTrim, userId, isUnique);
            
            return isUnique;
        } catch (Exception e) {
            log.warn("缓存操作失败，直接从数据库查询，身份证号：{}，用户ID：{}", idCardTrim, userId, e);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getIdCard, idCardTrim);
            if (userId != null) {
                queryWrapper.ne(User::getId, userId);
            }
            return this.count(queryWrapper) == 0;
        }
    }

    @Override
    public boolean checkUsernameExists(String username) throws Exception {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        return this.count(queryWrapper) > 0;
    }

    @Override
    public boolean checkPhoneExists(String phone) throws Exception {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        return this.count(queryWrapper) > 0;
    }

    @Override
    public boolean checkEmailExists(String email) throws Exception {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, email);
        return this.count(queryWrapper) > 0;
    }

    @Override
    @GlobalTransactional
    public void updateUserStatus(Long userId, Integer status) throws Exception {
        // 查询现有用户，保留版本号以确保乐观锁正常工作
        User existingUser = this.getById(userId);
        if (existingUser == null) {
            throw new BusinessException("用户不存在");
        }
        
        existingUser.setStatus(status);
        existingUser.setUpdateTime(LocalDateTime.now());
        this.updateById(existingUser);
    }

    @Override
    public com.smart.community.user.vo.UserRoleAssignVO getUserRoleAssignInfo(Long userId) throws Exception {
        com.smart.community.user.vo.UserRoleAssignVO vo = new com.smart.community.user.vo.UserRoleAssignVO();
        User user = this.getById(userId);
        if (user == null) {
            return vo;
        }
        vo.setUserId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setRealName(user.getRealName());
        vo.setPhone(user.getPhone());
        vo.setEmail(user.getEmail());
        // 当前角色ID列表
        List<com.smart.community.user.entity.UserRole> userRoles = userRoleService.getUserRolesByUserId(userId);
        List<Long> currentRoleIds = new ArrayList<>();
        List<String> currentRoleNames = new ArrayList<>();
        if (userRoles != null) {
            for (com.smart.community.user.entity.UserRole ur : userRoles) {
                if (ur != null && ur.getRoleId() != null) {
                    currentRoleIds.add(ur.getRoleId());
                    // 查询角色名称
                    com.smart.community.user.vo.RoleVO roleVO = roleService.getRole(ur.getRoleId());
                    if (roleVO != null && roleVO.getRoleName() != null) {
                        currentRoleNames.add(roleVO.getRoleName());
                    }
                }
            }
        }
        vo.setCurrentRoleIds(currentRoleIds);
        vo.setCurrentRoleNames(currentRoleNames);
        // 可用角色列表
        List<com.smart.community.user.vo.RoleVO> availableRoles = new ArrayList<>();
        try {
            com.smart.community.user.dto.RoleQueryDTO roleQueryDTO = new com.smart.community.user.dto.RoleQueryDTO();
            roleQueryDTO.setCurrent(1);
            roleQueryDTO.setSize(1000); // 设置较大的页面大小以获取所有角色
            com.smart.community.user.vo.PageResult<com.smart.community.user.vo.RoleVO> rolePageResult = roleService.getRoleList(roleQueryDTO);
            if (rolePageResult != null && rolePageResult.getRecords() != null) {
                availableRoles = rolePageResult.getRecords();
            }
        } catch (Exception e) {
            // 记录错误但不影响主流程
            log.warn("获取可用角色列表失败", e);
        }
        vo.setAvailableRoles(availableRoles);
        return vo;
    }

    /**
     * 将User实体转换为UserVO
     * 
     * @param user 用户实体
     * @return 用户VO
     */
    private UserVO convertToUserVO(User user) {
        if (user == null) {
            return null;
        }
        
        UserVO userVO = new UserVO();
        userVO.setId(user.getId());
        userVO.setUsername(user.getUsername());
        userVO.setRealName(user.getRealName());
        userVO.setEmail(user.getEmail());
        userVO.setPhone(user.getPhone());
        userVO.setUserType(user.getUserType());
        userVO.setStatus(user.getStatus());
        userVO.setCreateTime(user.getCreateTime());
        
        return userVO;
    }

    @Override
    @GlobalTransactional
    public void addPropertyCompanyUser(Map<String, Object> userData) throws Exception {
        // 物业公司ID为空直接打回
        Object pci = userData.get("propertyCompanyId");
        if (pci == null) {
            log.warn("propertyCompanyId：{}， 新增物业公司用户失败", pci);
            throw new BusinessException("物业公司ID不能为空");
        }
        log.info("新增物业公司用户，用户数据：{}", userData);
        long propertyCompanyId = ((BigInteger) pci).longValue();
        // 获取当前用户ID
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            log.warn("获取当前用户ID失败，新增物业公司用户失败");
            throw new BusinessException("获取当前用户ID失败");
        }
        
        // 检查用户名重复
        String username = (String) userData.get("username");
        if (username != null && !username.trim().isEmpty()) {
            if (!checkUsernameUnique(username.trim(), null)) {
                log.warn("用户名重复，用户名：{}", username.trim());
                throw new BusinessException("用户名已存在，请使用其他用户名");
            }
        } else {
            log.warn("用户名为空，新增物业公司用户失败");
            throw new BusinessException("用户名不能为空");
        }
        
        // 检查身份证号重复
        String idCard = (String) userData.get("idCard");
        if (idCard != null && !idCard.trim().isEmpty()) {
            if (!checkIdCardUnique(idCard.trim(), null)) {
                log.warn("身份证号重复，身份证号：{}", idCard.trim());
                throw new BusinessException("身份证号已存在，请检查后重新输入");
            }
        }
        
        // 检查手机号重复
        String phone = (String) userData.get("phone");
        if (phone != null && !phone.trim().isEmpty()) {
            if (!checkPhoneUnique(phone.trim(), null)) {
                log.warn("手机号重复，手机号：{}", phone.trim());
                throw new BusinessException("手机号已存在，请使用其他手机号");
            }
        }
        
        // 1. 创建用户实体
        User user = new User();
        user.setUsername((String) userData.get("username"));
        user.setRealName((String) userData.get("realName"));
        user.setPhone(phone);
        user.setEmail((String) userData.get("email"));
        user.setIdCard(idCard);
        user.setUserType((String) userData.get("userType"));
        user.setStatus(SystemStatusEnum.ENABLED.getCode());
        user.setPropertyCompanyId(null);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setPropertyCompanyId(propertyCompanyId);
        user.setCreateBy(currentUserId);
        
        // 2. 设置默认密码
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        
        // 3. 保存用户
        this.save(user);
        
        // 4. 根据用户类型设置角色
        String userType = user.getUserType();
        Long roleId = getUserTypeRoleId(userType);
        if (roleId != null) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            userRoleService.save(userRole);
        }
        
        // 5. 关联物业公司
        userPropertyCompanyService.associateUserWithCompany(user.getId(), propertyCompanyId);
        
        // 清除相关缓存
        try {
            // 清除物业公司用户列表缓存
            clearPropertyCompanyUsersCache(propertyCompanyId);
            
            // 清除用户物业公司关联缓存
            String userPropertyCompaniesCacheKey = USER_PROPERTY_COMPANIES_CACHE_PREFIX + user.getId();
            cacheService.delete(userPropertyCompaniesCacheKey);
            
            log.debug("新增物业公司用户成功，已清除相关缓存，用户ID：{}，物业公司ID：{}", user.getId(), propertyCompanyId);
        } catch (Exception e) {
            log.warn("清除新增物业公司用户相关缓存失败，用户ID：{}，物业公司ID：{}", user.getId(), propertyCompanyId, e);
        }
        
        log.info("新增物业公司用户成功，用户ID：{}", user.getId());
    }

    @Override
    public PageResult<UserVO> getPropertyCompanyUsers(Long propertyCompanyId, Integer current, Integer size) throws Exception {
        log.info("获取物业公司用户列表，物业公司ID：{}，当前页：{}，页大小：{}", propertyCompanyId, current, size);
        
        String cacheKey = PROPERTY_COMPANY_USERS_CACHE_PREFIX + propertyCompanyId + ":" + current + ":" + size;
        
        try {
            // 尝试从缓存获取
            @SuppressWarnings("unchecked")
            PageResult<UserVO> cachedResult = cacheService.get(cacheKey, PageResult.class);
            if (cachedResult != null) {
                log.debug("从缓存获取物业公司用户列表成功，物业公司ID：{}", propertyCompanyId);
                return cachedResult;
            }
            
            // 缓存未命中，从数据库查询
            // 1. 获取物业公司关联的用户列表
            List<UserPropertyCompanyVO> userPropertyCompanies = userPropertyCompanyService.getPropertyCompanyUsers(propertyCompanyId);
            if (userPropertyCompanies.isEmpty()) {
                PageResult<UserVO> emptyResult = new PageResult<>(current, size, 0L, new ArrayList<>());
                // 缓存空结果
                cacheService.set(cacheKey, emptyResult, PROPERTY_COMPANY_USERS_CACHE_EXPIRE);
                return emptyResult;
            }
            
            // 提取用户ID列表
            List<Long> userIds = new ArrayList<>();
            for (UserPropertyCompanyVO vo : userPropertyCompanies) {
                if (vo.getUserId() != null) {
                    userIds.add(vo.getUserId());
                }
            }
            
            // 2. 分页查询用户信息
            Page<User> page = new Page<>(current, size);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(User::getId, userIds);
            queryWrapper.orderByDesc(User::getUpdateTime);
            
            IPage<User> userPage = this.page(page, queryWrapper);
            
            // 3. 转换为VO
            List<UserVO> userVOList = new ArrayList<>();
            for (User user : userPage.getRecords()) {
                userVOList.add(convertToUserVO(user));
            }
            
            PageResult<UserVO> result = new PageResult<>(current, size, userPage.getTotal(), userVOList);
            
            // 缓存查询结果
            cacheService.set(cacheKey, result, PROPERTY_COMPANY_USERS_CACHE_EXPIRE);
            log.debug("物业公司用户列表已缓存，物业公司ID：{}", propertyCompanyId);
            
            return result;
        } catch (Exception e) {
            log.warn("缓存操作失败，直接从数据库查询，物业公司ID：{}", propertyCompanyId, e);
            // 1. 获取物业公司关联的用户列表
            List<UserPropertyCompanyVO> userPropertyCompanies = userPropertyCompanyService.getPropertyCompanyUsers(propertyCompanyId);
            if (userPropertyCompanies.isEmpty()) {
                return new PageResult<>(current, size, 0L, new ArrayList<>());
            }
            
            // 提取用户ID列表
            List<Long> userIds = new ArrayList<>();
            for (UserPropertyCompanyVO vo : userPropertyCompanies) {
                if (vo.getUserId() != null) {
                    userIds.add(vo.getUserId());
                }
            }
            
            // 2. 分页查询用户信息
            Page<User> page = new Page<>(current, size);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(User::getId, userIds);
            queryWrapper.orderByDesc(User::getUpdateTime);
            
            IPage<User> userPage = this.page(page, queryWrapper);
            
            // 3. 转换为VO
            List<UserVO> userVOList = new ArrayList<>();
            for (User user : userPage.getRecords()) {
                userVOList.add(convertToUserVO(user));
            }
            
            return new PageResult<>(current, size, userPage.getTotal(), userVOList);
        }
    }

    @Override
    @GlobalTransactional
    public void enablePropertyCompanyUser(Long userId) throws Exception {
        log.info("启用物业公司用户，用户ID：{}", userId);
        updateUserStatus(userId, 1);
    }

    @Override
    @GlobalTransactional
    public void disablePropertyCompanyUser(Long userId) throws Exception {
        log.info("禁用物业公司用户，用户ID：{}", userId);
        updateUserStatus(userId, 0);
    }

    @Override
    @GlobalTransactional
    public void resetPropertyCompanyUserPassword(Long userId) throws Exception {
        log.info("重置物业公司用户密码，用户ID：{}", userId);
        resetPassword(userId, "123456");
    }

    @Override
    public List<User> getUsersByDataPermission(Long currentUserId, UserQueryDTO queryDTO) throws Exception {
        log.info("根据数据权限查询用户列表，当前用户ID：{}，查询条件：{}", currentUserId, queryDTO);
        
        try {
            // 获取当前用户的数据权限信息
            DataScopeInfo dataScopeInfo = dataScopeFeign.getUserDataScope(currentUserId);
            log.info("用户数据权限信息：{}", dataScopeInfo);
            
            // 根据数据权限构建查询条件
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            
            // 根据用户权限范围过滤数据
            if (dataScopeInfo.isSuperAdmin()) {
                // 超级管理员：可以查看所有用户
                log.debug("超级管理员权限，查询所有用户");
            } else if (dataScopeInfo.isPropertyCompanyUser()) {
                // 物业公司用户：只能查看本公司用户
                List<Long> propertyCompanyIds = dataScopeInfo.getPropertyCompanyIds();
                if (propertyCompanyIds != null && !propertyCompanyIds.isEmpty()) {
                    queryWrapper.in(User::getPropertyCompanyId, propertyCompanyIds);
                    log.debug("物业公司用户权限，查询物业公司ID：{}", propertyCompanyIds);
                }
            } else if (dataScopeInfo.isOwnerUser()) {
                // 业主用户：只能查看关联社区的用户
                List<Long> communityIds = dataScopeInfo.getCommunityIds();
                if (communityIds != null && !communityIds.isEmpty()) {
                    queryWrapper.in(User::getCommunityId, communityIds);
                    log.debug("业主用户权限，查询社区ID：{}", communityIds);
                }
            } else {
                // 普通用户：只能查看自己的信息
                queryWrapper.eq(User::getId, currentUserId);
                log.debug("普通用户权限，只能查看自己的信息");
            }
            
            // 添加查询条件
            if (queryDTO != null) {
                if (queryDTO.getUsername() != null && !queryDTO.getUsername().trim().isEmpty()) {
                    queryWrapper.like(User::getUsername, queryDTO.getUsername().trim());
                }
                if (queryDTO.getRealName() != null && !queryDTO.getRealName().trim().isEmpty()) {
                    queryWrapper.like(User::getRealName, queryDTO.getRealName().trim());
                }
                if (queryDTO.getPhone() != null && !queryDTO.getPhone().trim().isEmpty()) {
                    queryWrapper.like(User::getPhone, queryDTO.getPhone().trim());
                }
                if (queryDTO.getUserType() != null) {
                    queryWrapper.eq(User::getUserType, queryDTO.getUserType());
                }
                if (queryDTO.getStatus() != null) {
                    queryWrapper.eq(User::getStatus, queryDTO.getStatus());
                }
            }
            
            // 只查询启用状态的用户
            queryWrapper.eq(User::getStatus, SystemStatusEnum.ENABLED.getCode());
            
            // 执行查询
            List<User> users = this.list(queryWrapper);
            log.info("根据数据权限查询用户列表成功，当前用户ID：{}，查询结果数量：{}", currentUserId, users.size());
            
            return users;
        } catch (Exception e) {
            log.warn("根据数据权限查询用户列表失败，当前用户ID：{}", currentUserId, e);
            return new ArrayList<>();
        }
    }

    @Override
    public User getUserByIdCard(String idCard) throws Exception {
        if (idCard == null || idCard.trim().isEmpty()) {
            return null;
        }
        
        String idCardTrim = idCard.trim();
        String cacheKey = USER_ID_CARD_CACHE_PREFIX + idCardTrim;
        
        try {
            // 尝试从缓存获取
            User cachedUser = cacheService.get(cacheKey, User.class);
            if (cachedUser != null) {
                log.debug("从缓存获取用户信息成功，身份证号：{}", idCardTrim);
                return cachedUser;
            }
            
            // 缓存未命中，从数据库查询
            User user = baseMapper.selectByIdCard(idCardTrim);
            if (user != null) {
                // 缓存查询结果
                cacheService.set(cacheKey, user, USER_CACHE_EXPIRE);
                log.debug("用户信息已缓存，身份证号：{}", idCardTrim);
            }
            
            return user;
        } catch (Exception e) {
            log.warn("缓存操作失败，直接从数据库查询，身份证号：{}", idCardTrim, e);
            return baseMapper.selectByIdCard(idCardTrim);
        }
    }

    @Override
    public User getUserByPhone(String phone) throws Exception {
        if (phone == null || phone.trim().isEmpty()) {
            log.warn("手机号为空，无法查询用户");
            return null;
        }
        
        String phoneTrim = phone.trim();
        String cacheKey = USER_PHONE_CACHE_PREFIX + phoneTrim;
        
        try {
            // 尝试从缓存获取
            User cachedUser = cacheService.get(cacheKey, User.class);
            if (cachedUser != null) {
                log.debug("从缓存获取用户信息成功，手机号：{}", phoneTrim);
                return cachedUser;
            }
            
            // 缓存未命中，从数据库查询
            User user = baseMapper.selectByPhone(phoneTrim);
            if (user != null) {
                // 缓存查询结果
                cacheService.set(cacheKey, user, USER_CACHE_EXPIRE);
                log.debug("用户信息已缓存，手机号：{}", phoneTrim);
            }
            
            if (user != null) {
                log.debug("根据手机号查询用户成功，手机号：{}，用户ID：{}", phoneTrim, user.getId());
            } else {
                log.debug("根据手机号未找到用户，手机号：{}", phoneTrim);
            }
            return user;
        } catch (Exception e) {
            log.warn("缓存操作失败，直接从数据库查询，手机号：{}", phoneTrim, e);
            try {
                User user = baseMapper.selectByPhone(phoneTrim);
                if (user != null) {
                    log.debug("根据手机号查询用户成功，手机号：{}，用户ID：{}", phoneTrim, user.getId());
                } else {
                    log.debug("根据手机号未找到用户，手机号：{}", phoneTrim);
                }
                return user;
            } catch (Exception dbException) {
                log.error("根据手机号查询用户失败，手机号：{}，错误：{}", phoneTrim, dbException.getMessage(), dbException);
                throw new Exception("查询用户失败：" + dbException.getMessage());
            }
        }
    }

    @Override
    @GlobalTransactional
    public Long createNormalUser(com.smart.community.feign.user.dto.NormalUserCreateDTO dto) throws Exception {
        try {
            // 1. 基本校验与唯一性检查
            if (dto.getPhone() != null && !dto.getPhone().trim().isEmpty()) {
                if (!checkPhoneUnique(dto.getPhone().trim(), null)) {
                    throw new BusinessException("手机号重复");
                }
            }
            if (dto.getIdCard() != null && !dto.getIdCard().trim().isEmpty()) {
                if (!checkIdCardUnique(dto.getIdCard().trim(), null)) {
                    throw new BusinessException("身份证号重复");
                }
            }

            // 2. 组装User实体
            User user = new User();
            user.setUsername(dto.getUsername());
            user.setRealName(dto.getRealName());
            user.setPhone(dto.getPhone());
            user.setEmail(dto.getEmail());
            user.setIdCard(dto.getIdCard());
            user.setGender(dto.getGender());
            user.setBirthday(dto.getBirthday());

            // 3. 用户类型与状态按权威标准设置
            user.setUserType(RoleCodeEnum.NORMAL_USER.getCode());
            user.setStatus(com.smart.community.commons.enums.SystemStatusEnum.ENABLED.getCode());
            user.setAuditStatus(com.smart.community.commons.enums.SystemStatusEnum.AUDIT_APPROVED.getCode());
            user.setIsAdminProtected(0);

            // 4. 密码加密（若未显式提供，则默认123456）
            String rawPwd = (dto.getPassword() != null && !dto.getPassword().isEmpty()) ? dto.getPassword() : "123456";
            user.setPassword(SecurityUtils.encryptPassword(rawPwd));

            // 5. 创建信息：Feign接口禁止从上下文取用户，使用显式传入的operatorId
            if (dto.getOperatorId() != null) {
                user.setCreateBy(dto.getOperatorId());
                user.setUpdateBy(dto.getOperatorId());
            }

            // 6. 持久化
            boolean saved = this.save(user);
            if (!saved) {
                throw new BusinessException("保存用户失败");
            }

            // 7. 分配NORMAL_USER角色
            List<Long> roleIds = new ArrayList<>();
            roleIds.add(13L);
            userRoleService.assignRolesToUser(user.getId(), roleIds);

            log.info("创建普通用户成功，用户ID：{}", user.getId());
            return user.getId();
        } catch (Exception e) {
            log.error("创建普通用户失败", e);
            throw new Exception("创建普通用户失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户类型获取对应的角色ID
     * 
     * @param userType 用户类型
     * @return 角色ID
     */
    private Long getUserTypeRoleId(String userType) {
        switch (userType) {
            case "COMMUNITY_ADMIN": return 3L;
            case "PROPERTY_STAFF": return 4L;
            case "SECURITY_STAFF": return 5L;
            case "REPAIR_STAFF": return 6L;
            case "RESIDENT": return 7L;
            case "PROPERTY_ADMIN": return 9L;
            case "BUILDING_ADMIN": return 10L;
            case "UNIT_ADMIN": return 11L;
            case "HOUSEHOLD_ADMIN": return 12L;
            case "NORMAL_USER": return 13L;
            default: return null;
        }
    }

    @Override
    public List<User> getUsersByRoleCode(String roleCode) throws Exception {
        log.info("根据角色编码获取用户列表，角色编码：{}", roleCode);
        
        // 根据角色编码获取角色ID
        Long roleId = roleService.getRoleIdByCode(roleCode);
        if (roleId == null) {
            log.warn("角色编码不存在，角色编码：{}", roleCode);
            return new ArrayList<>();
        }
        
        // 根据角色ID获取用户列表
        return userRoleService.getUsersByRoleId(roleId);
    }
    
    // ==================== 用户统计方法实现 ====================
    
    @Override
    public Long countUsersByCommunityIds(List<Long> communityIds) throws Exception {
        log.info("根据社区ID列表统计用户数量，社区ID列表：{}", communityIds);
        
        try {
            if (communityIds == null || communityIds.isEmpty()) {
                return 0L;
            }
            
            // 这里需要根据实际的数据库表结构来实现
            // 假设用户表中有community_id字段，或者通过关联表查询
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(User::getCommunityId, communityIds);
            queryWrapper.eq(User::getStatus, SystemStatusEnum.ENABLED.getCode());
            
            long count = this.count(queryWrapper);
            log.info("根据社区ID列表统计用户数量成功，社区ID列表：{}，用户数量：{}", communityIds, count);
            return count;
        } catch (Exception e) {
            log.warn("根据社区ID列表统计用户数量失败，社区ID列表：{}", communityIds, e);
            return 0L;
        }
    }
    
    @Override
    public Long countUsersByPropertyCompanyIds(List<Long> propertyCompanyIds) throws Exception {
        log.info("根据物业公司ID列表统计用户数量，物业公司ID列表：{}", propertyCompanyIds);
        
        try {
            if (propertyCompanyIds == null || propertyCompanyIds.isEmpty()) {
                return 0L;
            }
            
            // 通过用户物业公司关联表查询
            // 查询用户物业公司关联表中，指定物业公司ID列表下的用户数量
            LambdaQueryWrapper<UserPropertyCompany> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(UserPropertyCompany::getPropertyCompanyId, propertyCompanyIds);
            queryWrapper.eq(UserPropertyCompany::getStatus, 1); // 1-在职状态
            
            // 使用UserPropertyCompanyMapper的count方法（BaseMapper提供的方法）
            long count = userPropertyCompanyMapper.selectCount(queryWrapper);
            log.info("根据物业公司ID列表统计用户数量成功，物业公司ID列表：{}，用户数量：{}", propertyCompanyIds, count);
            return count;
        } catch (Exception e) {
            log.warn("根据物业公司ID列表统计用户数量失败，物业公司ID列表：{}", propertyCompanyIds, e);
            return 0L;
        }
    }
    
    @Override
    public Long countUsersByHouseholdIds(List<Long> householdIds) throws Exception {
        log.info("根据房户ID列表统计用户数量，房户ID列表：{}", householdIds);
        
        try {
            if (householdIds == null || householdIds.isEmpty()) {
                return 0L;
            }
            
            // 这里需要根据实际的数据库表结构来实现
            // 假设用户表中有household_id字段，或者通过关联表查询
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(User::getHouseholdId, householdIds);
            queryWrapper.eq(User::getStatus, SystemStatusEnum.ENABLED.getCode());
            
            long count = this.count(queryWrapper);
            log.info("根据房户ID列表统计用户数量成功，房户ID列表：{}，用户数量：{}", householdIds, count);
            return count;
        } catch (Exception e) {
            log.warn("根据房户ID列表统计用户数量失败，房户ID列表：{}", householdIds, e);
            return 0L;
        }
    }
    
    @Override
    public List<Integer> getUserRegistrationTrend(List<Long> communityIds, int months) throws Exception {
        log.info("获取用户注册趋势数据，社区ID列表：{}，统计月份数：{}", communityIds, months);
        
        try {
            if (communityIds == null || communityIds.isEmpty()) {
                return generateEmptyDataList(months);
            }
            
            // 这里需要根据实际的数据库表结构来实现
            // 暂时返回模拟数据
            List<Integer> trendData = new ArrayList<>();
            for (int i = 0; i < months; i++) {
                trendData.add((int) (Math.random() * 100 + 50)); // 模拟50-150之间的随机数
            }
            
            log.info("获取用户注册趋势数据成功，社区ID列表：{}，趋势数据：{}", communityIds, trendData);
            return trendData;
        } catch (Exception e) {
            log.warn("获取用户注册趋势数据失败，社区ID列表：{}", communityIds, e);
            return generateEmptyDataList(months);
        }
    }
    
    @Override
    public Long getTotalUserCount() throws Exception {
        log.info("获取所有用户总数");
        
        try {
            // 统计所有启用的用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getStatus, SystemStatusEnum.ENABLED.getCode());
            
            long count = this.count(queryWrapper);
            log.info("获取所有用户总数成功，用户总数：{}", count);
            return count;
        } catch (Exception e) {
            log.warn("获取所有用户总数失败", e);
            return 0L;
        }
    }
    
    @Override
    public List<Integer> getUserRegistrationTrendForAll(int months) throws Exception {
        log.info("获取所有用户注册趋势数据，统计月份数：{}", months);
        
        try {
            // 这里需要根据实际的数据库表结构来实现
            // 暂时返回模拟数据
            List<Integer> trendData = new ArrayList<>();
            for (int i = 0; i < months; i++) {
                trendData.add((int) (Math.random() * 200 + 100)); // 模拟100-300之间的随机数
            }
            
            log.info("获取所有用户注册趋势数据成功，趋势数据：{}", trendData);
            return trendData;
        } catch (Exception e) {
            log.warn("获取所有用户注册趋势数据失败", e);
            return generateEmptyDataList(months);
        }
    }
    
    /**
     * 生成指定长度的空数据列表
     * 
     * @param size 列表大小
     * @return 填充0的列表
     */
    private List<Integer> generateEmptyDataList(int size) {
        List<Integer> emptyList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            emptyList.add(0);
        }
        return emptyList;
    }
} 